package cn.infozr.api.client;

import java.util.UUID;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.TreeMap;

/**
 * 门店基本信息完善接口客户端
 * 用于测试 https://IP:端口/ygydapi/v1/editSubStoreInfo 接口
 */
public class StoreInfoUpdateApiClient extends BaseClient {
    
    /**
     * 门店基本信息完善请求参数类
     */
    public static class StoreInfoUpdateRequest {
        private String appId;
        private String timestamp;
        private String reqId;
        private String uscc;
        private String sfyb;
        private String yysj;
        private String lxdh;
        private String longitude;
        private String latitude;
        private String img;
        private String sign;
        
        // 构造函数
        public StoreInfoUpdateRequest() {
            this.timestamp = String.valueOf(System.currentTimeMillis());
            this.reqId = UUID.randomUUID().toString().replace("-", "");
        }
        
        // Getters and Setters
        public String getAppId() { return appId; }
        public void setAppId(String appId) { this.appId = appId; }
        
        public String getTimestamp() { return timestamp; }
        public void setTimestamp(String timestamp) { this.timestamp = timestamp; }
        
        public String getReqId() { return reqId; }
        public void setReqId(String reqId) { this.reqId = reqId; }
        
        public String getUscc() { return uscc; }
        public void setUscc(String uscc) { this.uscc = uscc; }
        
        public String getSfyb() { return sfyb; }
        public void setSfyb(String sfyb) { this.sfyb = sfyb; }
        
        public String getYysj() { return yysj; }
        public void setYysj(String yysj) { this.yysj = yysj; }
        
        public String getLxdh() { return lxdh; }
        public void setLxdh(String lxdh) { this.lxdh = lxdh; }
        
        public String getLongitude() { return longitude; }
        public void setLongitude(String longitude) { this.longitude = longitude; }
        
        public String getLatitude() { return latitude; }
        public void setLatitude(String latitude) { this.latitude = latitude; }
        
        public String getImg() { return img; }
        public void setImg(String img) { this.img = img; }
        
        public String getSign() { return sign; }
        public void setSign(String sign) { this.sign = sign; }
    }
    
    /**
     * 生成数据签名
     * @param request 请求参数对象
     * @return 签名字符串
     * @throws Exception 加密异常
     */
    protected String generateSign(StoreInfoUpdateRequest request) throws Exception {
        // 按照字段名的字典序拼接参数
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", request.getAppId());
        params.put("reqId", request.getReqId());
        params.put("timestamp", request.getTimestamp());
        params.put("uscc", request.getUscc());
        params.put("sfyb", request.getSfyb());
        params.put("yysj", request.getYysj());
        params.put("lxdh", request.getLxdh());
        params.put("longitude", request.getLongitude());
        params.put("latitude", request.getLatitude());
        
        if (request.getImg() != null && !request.getImg().isEmpty()) {
            params.put("img", request.getImg());
        }
        
        return cn.infozr.api.util.SM3SignatureUtil.generateSignature(params, SECRET_KEY);
    }
    
    /**
     * 调用门店基本信息完善接口
     * @param uscc 药店18位统一社会信用代码
     * @param sfyb 是否医保定点药店(1是2否)
     * @param yysj 营业时间范围，格式08:00~23:00
     * @param lxdh 门店对外展示的联系电话
     * @param longitude 经度
     * @param latitude 纬度
     * @param img 门头照片，base64格式(可选)
     * @return 接口响应结果
     * @throws Exception 网络或解析异常
     */
    public String updateStoreInfo(String uscc, String sfyb, String yysj, String lxdh, 
                                  String longitude, String latitude, String img) throws Exception {
        // 构造请求参数
        StoreInfoUpdateRequest request = new StoreInfoUpdateRequest();
        request.setAppId(APP_ID);
        request.setTimestamp(String.valueOf(System.currentTimeMillis()));
        request.setUscc(uscc);
        request.setSfyb(sfyb);
        request.setYysj(yysj);
        request.setLxdh(lxdh);
        request.setLongitude(longitude);
        request.setLatitude(latitude);
        request.setImg(img);
        
        // 生成签名
        request.setSign(generateSign(request));
        
        // 发送POST请求
        return sendPostRequest(STORE_INFO_UPDATE_API_URL, request);
    }
    
    /**
     * 发送POST请求
     * @param url 请求地址
     * @param request 请求参数对象
     * @return 响应结果
     * @throws Exception 网络异常
     */
    protected String sendPostRequest(String url, StoreInfoUpdateRequest request) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法和请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);

        // 序列化请求参数，过滤空值
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        String jsonInputString = objectMapper.writeValueAsString(request);
        System.out.println("请求参数: " + jsonInputString);
        
        // 发送请求
        try(OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = con.getResponseCode();
        // 读取响应
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return response.toString();
            }
        } else {
            // 读取错误响应
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(con.getErrorStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.err.println("错误响应: " + response.toString());
                return "{\"code\":" + responseCode + ",\"msg\":\"请求失败\"}";
            }
        }
    }
    
    /**
     * 解析并打印门店信息更新结果
     * @param jsonResponse JSON响应字符串
     * @throws Exception 解析异常
     */
    public void parseAndPrintUpdateResult(String jsonResponse) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(jsonResponse);
        
        System.out.println("接口响应:");
        System.out.println("状态码: " + (rootNode.has("code") ? rootNode.get("code").asText() : "无"));
        System.out.println("消息提示: " + (rootNode.has("msg") ? rootNode.get("msg").asText() : "无"));
        System.out.println("请求ID: " + (rootNode.has("reqId") ? rootNode.get("reqId").asText() : "无"));
        System.out.println("数据体: " + (rootNode.has("data") ? rootNode.get("data").toString() : "无"));
    }
    
    /**
     * 主方法 - 测试接口调用
     */
    public static void main(String[] args) {
        try {
            StoreInfoUpdateApiClient client = new StoreInfoUpdateApiClient();
            
            // 构造测试数据
            String uscc = "913401007608485412"; // 药店统一社会信用代码
            String sfyb = "1"; // 是否医保定点药店(1是2否)
            String yysj = "08:00~23:01"; // 营业时间范围
            String lxdh = "0551-88888888"; // 联系电话
            String longitude = "117.227219"; // 经度
            String latitude = "31.820591"; // 纬度
            String img = ""; // 门头照片base64，此处为空
            
            System.out.println("正在完善门店基本信息...");
            String result = client.updateStoreInfo(uscc, sfyb, yysj, lxdh, longitude, latitude, img);
            
            // 解析并打印结果
            client.parseAndPrintUpdateResult(result);
            
        } catch (Exception e) {
            System.err.println("门店信息完善操作时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}